<!--
 * @description 个人档案
 * @author dumeng
 * @date 2022/3/18
 -->
<template>
  <div class="craftsman-record-page">
    <el-dialog
      custom-class="craftsman-record-timeline"
      :close-on-click-modal="false"
      :show-close="false"
      :visible.sync="visible"
      fullscreen
      center
      :before-close="handleCancel"
    >
      <div slot="title" class="record-title">
        <span>个人档案</span>
        <el-button class="export" @click="handleImport">批量导入</el-button>
        <el-button
          type="primary"
          class="insert"
          @click="(dialogVisible4manage = true), resetForm(),(type='c')"
        >新增个人档案</el-button>
      </div>
      <div v-if="isShowBox" class="isShowBox">
        暂无档案请添加档案
      </div>
      <section class="record-page-main">
        <el-timeline>
          <el-timeline-item
            v-for="item in list"
            :key="item.id"
            :timestamp="setTime(item)"
            placement="top"
            :color="'#e44d42'"
          >
            <el-card class="record-container">
              <div class="btns-container">
                <el-button type="text" @click="handleUpdate(item)">编辑</el-button>
                <el-button type="text" @click="handleDelete(item)">删除</el-button>
              </div>
              <h4>{{ item.recordTypeName }}</h4>
              <p>{{ item.recordDesc }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </section>
      <div slot="footer" class="dialog-footer">
        <el-button
          style="padding: 8px 30px"
          @click="$emit('close')"
        >关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-el-drag-dialog
      custom-class="craftsman-record-manage"
      append-to-body
      center
      title="新增/编辑个人档案"
      width="800px"
      :visible.sync="dialogVisible4manage"
    >
      <section v-loading="loading" class="form-inner">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="100px"
          class="form"
        >
          <el-form-item label="开始时间" prop="time">
            <el-row :gutter="20">
              <el-col :span="7">
                <el-form-item label="年" label-width="auto" prop="startYear">
                  <el-date-picker
                    v-model="form.startYear"
                    type="year"
                    value-format="yyyy"
                    placeholder="请选择年"
                    :style="{ width: '100%' }"
                    @change="handelChangeSetTime('start')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="月" label-width="auto" prop="startMonth">
                  <el-select
                    v-model="form.startMonth"
                    :disabled="!form.startYear"
                    placeholder="请选择月"
                    clearable
                    :style="{ width: '100%' }"
                    @change="handleGetDayList()"
                    @clear="handelClear('startMonth')"
                  >
                    <el-option
                      v-for="item in monthList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="日" label-width="auto" prop="startMonth">
                  <el-select
                    v-model="form.startDay"
                    :disabled="!form.startMonth"
                    placeholder="请选择日期"
                    clearable
                    :style="{ width: '100%' }"
                    @change="handelChangeSetTime('start')"
                    @clear="handelClear('startDay')"
                  >
                    <el-option
                      v-for="item in startAllDay"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="结束时间" prop="time">
            <el-row :gutter="20">
              <el-col :span="7">
                <el-form-item label="年" label-width="auto" prop="endYear">
                  <el-date-picker
                    v-model="form.endYear"
                    :disabled="endTimeIsDisabeled"
                    type="year"
                    value-format="yyyy"
                    placeholder="请选择年"
                    :style="{ width: '100%' }"
                    @change="setDay('end')"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="月" label-width="auto" prop="endMonth">
                  <el-select
                    v-model="form.endMonth"
                    :disabled="endTimeIsDisabeled || !form.endYear"
                    placeholder="请选择月"
                    clearable
                    :style="{ width: '100%' }"
                    @change="setDay('end')"
                  >
                    <el-option
                      v-for="item in monthList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="日" label-width="auto" prop="endMonth">
                  <el-select
                    v-model="form.endDay"
                    :disabled="endTimeIsDisabeled || !form.endMonth"
                    placeholder="请选择日期"
                    clearable
                    :style="{ width: '100%' }"
                  >
                    <el-option
                      v-for="item in endAllDay"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-checkbox-group
                  v-model="flag"
                  :max="1"
                  @change="handelCheck()"
                >
                  <el-checkbox label="same">与开始时间一致</el-checkbox>
                  <el-checkbox label="toNow">至今</el-checkbox>
                </el-checkbox-group>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="类型" prop="recordType">
            <el-radio-group v-model="form.recordType">
              <el-radio v-for="item in dict.DALX" :key="item.dictValue" :value="item.dictValue" :label="item.dictValue">
                {{ item.dictName }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="描述" prop="recordDesc">
            <el-input
              v-model="form.recordDesc"
              :rows="6"
              type="textarea"
              maxlength="1000"
              show-word-limit
            />
          </el-form-item>
          <el-form-item label="排序" prop="recordSort">
            <el-input
              v-model="form.recordSort"
              placeholder="请输入排序号（值越大，越靠前）"
            />
          </el-form-item>
        </el-form>
      </section>
      <section slot="footer" class="dialog-footer">
        <el-button
          style="padding: 10px 30px"
          @click="dialogVisible4manage = false"
        >取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </section>
    </el-dialog>
    <el-dialog v-el-drag-dialog :close-on-click-modal="false" :visible.sync="dialogUploadVisible" title="上传文件" center width="500px" @close="handleClosed">
      <el-upload
        ref="upload"
        v-loading="loadingUpload"
        element-loading-text="正在上传请稍后"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :auto-upload="false"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :action="uploadaction"
        :headers="uploadHeaders"
        :data="uploadData"
        accept=".xls, .xlsx"
        class="upload-demo"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div slot="tip" class="el-upload__tip">
          只能上传.xls,.xlsx
          <el-button type="text" @click="handleDownload">下载模板</el-button>
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px;" type="primary" @click="handleClosed">取消</el-button>
        <el-button style="padding: 8px 30px;" type="primary" @click="submitUpload()">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { get, insertRecord, updateRecord, deleteRecord, getDictByCode } from './api.js'
import { exportSign, importSign } from '@/utils/fileImportOrExportSign'
export default {
  name: 'CraftsmanRecord',
  directives: { elDragDialog },
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      visible: true,
      dialogVisible4manage: false,
      list: [],
      startAllDay: '',
      endAllDay: '',
      monthList: [
        {
          label: '一月',
          value: 1
        },
        {
          label: '二月',
          value: 2
        },
        {
          label: '三月',
          value: 3
        },
        {
          label: '四月',
          value: 4
        },
        {
          label: '五月',
          value: 5
        },
        {
          label: '六月',
          value: 6
        },
        {
          label: '七月',
          value: 7
        },
        {
          label: '八月',
          value: 8
        },
        {
          label: '九月',
          value: 9
        },
        {
          label: '十月',
          value: 10
        },
        {
          label: '十一月',
          value: 11
        },
        {
          label: '十二月',
          value: 12
        }
      ],
      form: {
        startYear: '',
        startMonth: '',
        startDay: '',
        endYear: '',
        endMonth: '',
        endDay: '',
        recordType: '',
        recordDesc: '',
        recordSort: '',
        isUntil: ''
      },
      rules: {
        startYear: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        recordType: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        recordDesc: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ]
      },
      flag: [],
      endTimeIsDisabeled: false,
      dict: {
        DALX: []
      },
      type: 'c',
      isShowBox: false,
      dialogUploadVisible: false,
      loadingUpload: false,
      uploadData: {
        id: this.id
      },
      uploadaction: '/API-ENTERPRISE-BACKEND/backend/craftsmanLibrary/importCraftmanRecord',
      uploadHeaders: { ttsxbwqm: '', ttsxsjzc: '', ttsxyhcs: '' }
    }
  },
  created() {
    for (const key in this.dict) {
      this.getDict(key)
    }
    this.init()
  },
  methods: {
    /**
    * 获取字典
    */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(response => {
          this.dict[code] = (response.data.data && response.data.data.length > 0) ? response.data.data[0].list : []
        }).catch(error => {
          reject(error)
        })
      })
    },
    setDay(type, clear) {
      if (type === 'start') {
        this.form.startMonth = this.form.startYear ? this.form.startMonth : ''
        if (!clear) this.form.startDay = ''
        if (this.form.startYear && this.form.startMonth) {
          const month = parseInt(+this.form.startMonth, 10)
          const temp = new Date(+this.form.startYear, month, 0)
          this.startAllDay = temp.getDate()
        } else {
          this.startAllDay = ''
        }
      } else {
        this.form.endMonth = this.form.endYear ? this.form.endMonth : ''
        if (!clear) this.form.endDay = ''
        if (this.form.endYear && this.form.endMonth) {
          const month = parseInt(+this.form.endMonth, 10)
          const temp = new Date(+this.form.endYear, month, 0)
          this.endAllDay = temp.getDate()
        } else {
          this.endAllDay = ''
        }
      }
    },
    handelChangeSetTime(type, clear) {
      // 与开始时间一致
      if (this.flag.includes('same')) {
        this.endTimeIsDisabeled = true
        this.form.endYear = this.form.startYear
        if (this.form.startDay) {
          this.endAllDay = this.startAllDay
          this.form.endDay = this.form.startDay
        }
      } else if (this.flag.includes('toNow')) {
        // 至今
        this.endTimeIsDisabeled = true
        this.form.isUntil = '1'
      } else {
        this.endTimeIsDisabeled = false
      }
    },
    handleGetDayList(clear) {
      this.setDay('start', clear)
      if (this.flag.includes('same')) {
        this.form.endMonth = this.form.startMonth
      }
    },
    handelCheck() {
      this.handleGetDayList(true)
      this.handelChangeSetTime()
      if (this.flag.includes('toNow')) {
        this.form.endYear = ''
        this.form.endDay = ''
        this.form.endMonth = ''
      }
    },
    resetForm() {
      this.$nextTick(() => {
        for (const key in this.form) {
          this.form[key] = ''
        }
        this.$refs['form'].resetFields()

        this.flag = ['same']
      })
    },
    handleSubmit() {
      if (this.flag.includes('toNow') || this.form.endYear) {
        this.$refs['form'].validate((valitate) => {
          if (valitate) {
            const params = {}
            const form = Object.assign({}, this.form)
            if (this.flag.includes('toNow')) {
              delete form.endYear
              delete form.endDay
              delete form.endMonth
            }
            params.id = this.id
            params.records = JSON.stringify([form])
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            if (this.type === 'c') {
              insertRecord(params).then(
                res => {
                  loading.close()
                  if (res.data.code === '200') {
                    this.$message({
                      type: 'success',
                      message: '操作成功'
                    }
                    )
                    this.init()
                    this.dialogVisible4manage = false
                  }
                }
              ).catch(err => {
                loading.close(err)
              })
            } else if (this.type === 'u') {
              updateRecord(params).then(res => {
                loading.close()
                if (res.data.code === '200') {
                  this.$message({
                    type: 'success',
                    message: '操作成功'
                  }
                  )
                  this.init()
                  this.dialogVisible4manage = false
                }
              }).catch(err => {
                loading.close(err)
              })
            }
          } else {
            return false
          }
        })
      }
    },
    setTime(item) {
      const startTime = [item.startYear, item.startMonth, item.startDay]
      const endTime = [item.endYear, item.endMonth, item.endDay]
      const formData = ['年', '月', '日']
      let startstr = ''
      let endstr = ''
      for (let i = 0; i < startTime.length; i++) {
        if (startTime[i]) {
          startstr += startTime[i] + formData[i]
        } else {
          break
        }
      }

      for (let i = 0; i < endTime.length; i++) {
        if (endTime[i]) {
          endstr += endTime[i] + formData[i]
        } else {
          break
        }
      }
      if (startstr.trim() === endstr.trim()) {
        return startstr
      }
      if (item.isUntil === '1') {
        return `${startstr}  至今`
      }
      return startstr && endstr
        ? startstr + ' 至 ' + endstr
        : startstr || endstr
    },
    handleCancel() {},
    init() {
      let loading
      this.$nextTick(() => {
        loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
      })
      get({ id: this.id }).then(res => {
        loading.close()
        this.info = res.data.data
        this.list = this.info.record || []
        this.isShowBox = this.list.length < 1
      }).catch(err => loading.close(err))
    },
    handleDelete(row) {
      this.$confirm('此操作将删除这条档案信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          const params = {}
          params.id = this.id
          params.records = JSON.stringify([row])
          deleteRecord(params).then(() => {
            loading.close()
            this.$message({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.init()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      }).catch(() => {

      })
    },
    handleUpdate(row) {
      this.type = 'u'
      this.flag = []
      this.dialogVisible4manage = true
      this.$nextTick(() => {
        this.$refs['form'].resetFields()
        if (row.isUntil === '1') {
          this.endTimeIsDisabeled = true
          this.flag.push('toNow')
        } else if (row.startYear === row.endYear && row.startMonth === row.endMonth && row.startDay === row.endDay) {
          this.endTimeIsDisabeled = true
          this.flag.push('same')
        }
        this.form = Object.assign({}, row)
        this.setDay('start')
        this.setDay('end')
        this.form.startDay = row.startDay
        this.form.endDay = row.endDay

        // this.form.startMonth = row.endMonth
        // this.form.endMonth = row.endMonth
        this.$nextTick(() => {
          if (!row.startMonth) {
            this.$set(this.form, 'startMonth', '')
          } else {
            this.$set(this.form, 'startMonth', row.startMonth)
          }
          if (!this.form.recordSort) {
            this.$set(this.form, 'recordSort', '')
          } else {
            this.$set(this.form, 'recordSort', row.recordSort)
          }
          if (!row.endMonth) {
            this.$set(this.form, 'endMonth', '')
          } else {
            this.$set(this.form, 'endMonth', row.endMonth)
          }
        })
      })
    },
    submitUpload() {
      if (this.$refs['upload'].uploadFiles.length === 0) {
        this.$message.error('请上传文件')
      } else {
        this.loadingUpload = true
        this.uploadHeaders = importSign({}, { id: this.id })
        setTimeout(() => {
          this.$refs.upload.submit()
        }, 1000)
      }
    },
    handleDownload() {
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = '/API-ENTERPRISE-BACKEND/backend/craftsmanLibrary/downloadTemplate' + exportSign({ type: '1' }).paramStr
      link.setAttribute('download', '人物档案模版.xls')
      link.setAttribute('target', '_blank')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    handleImport() {
      this.dialogUploadVisible = true
    },
    handleUploadQues() {
      this.dialogUploadVisible = true
    },
    uploadSuccess(data) {
      this.loadingUpload = false
      if (data.code === '200') {
        this.$message({
          message: '导入成功',
          type: 'success'
        })
        this.dialogUploadVisible = false
        this.uploadQuesDialogVisible = false
        this.$refs.upload.clearFiles()
        this.init()
      } else {
        this.$message.error(data.msg || '网络异常')
        if (data.data.fileid) {
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = '/API-ENTERPRISE-BACKEND/backend/craftsmanLibrary/downloadCheckFile' + exportSign({ errorId: data.data.fileid }).paramStr
          link.setAttribute('download', '人物档案模版.xls')
          link.setAttribute('target', '_blank')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
        this.$refs.upload.clearFiles()
        if (data.data) {
          this.uploadErrorList = data.data
          this.dialogUploadErrorTextVisible = true
        }
      }
    },
    uploadError(err) {
      this.loadingUpload = false
      this.$message.error(err || '网络异常')
    },
    handelClear(type) {
      if (this.flag.includes('same')) {
        if (type === 'startYear') {
          this.form.endYear = ''
        } else if (type === 'startMonth') {
          this.form.endMonth = ''
        } else if (type === 'startDay') {
          this.form.endDay = ''
        }
      }
    },
    handleClosed() {
      this.dialogUploadVisible = false
      this.loadingUpload = false
      this.uploadQuesDialogVisible = false
      this.$refs.upload.clearFiles()
    }
  }
}
</script>

<style lang="scss">
.craftsman-record-page {
  position: relative;
  .craftsman-record-timeline {
    .record-title {
      position: relative;
      span {
        font-weight: bold;
      }
      .insert {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
      }
      .export {
        position: absolute;
        right: 200px;
        top: 50%;
        transform: translateY(-50%);
      }
    }
    .el-dialog__body {
      max-height: calc(100vh - 109px);
      min-height: calc(100vh - 109px);
      position: relative;
      overflow-y: auto;
      .record-page-main {
        width: 1000px;
        margin: 0 auto;
        padding: 10px;
        .record-container {
          position: relative;
          overflow: visible;
          .btns-container {
            position: absolute;
            right: 0;
            top: -34px;
          }
          h4 {
            margin-top: 0;
            margin-bottom: 10px;
            font-size: 16px;
          }
          p {
            margin: 0;
            white-space: pre-line;
          }

          .classify-tab {
            width: 100%;
            margin: 10px 0;
            padding: 0 10px;
            background-color: #fff;
            display: flex;
            border-radius: 4px;
            .el-tabs__nav-wrap::after {
              display: none;
            }
            .el-tabs__header {
              margin: 0;
            }
          }
        }
      }
    }
    .el-dialog__footer {
      padding: 10px 20px !important;
    }

    .isShowBox{
      display: flex;
      align-items: center;
      justify-content: center;
      height:500px;
      color:#333;
      font-weight: bold;
    }
  }
   .el-upload__tip{
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .upload-demo{
   display: flex;
   flex-direction: column;
   justify-content: center;
  }
}
.craftsman-record-manage {
  .form-inner {
    .el-form {
      height: 500px;
      overflow-y: auto;
    }
  }
}
</style>
